<template>
  <div class="second-step-container">
    <div class="form-title-wrap">
      <div class="form-title__left">{{ $t('smartPlan.conditionRangeGroup') }}</div>
      <el-button class="form-title__right" type="text" @click="openPreviewDialog">{{ $t('smartPlan.previewSelectResult') }}</el-button>
    </div>
    <base-select-condition
      v-if="isInit"
      ref="baseSelectCondition"
      :option-maps="optionMaps"
      :options-list="optionsList"
      :default-module="defaultModule"
      :default-condition-item="defaultConditionItem"
      max="20"
      module="createSmartPlan"
      :value="conditions"
      @cascaderChange="cascaderChange"
      @changeValue="changeValue"
      @removeItem="changeValue"
    ></base-select-condition>
    <div class="linkman-setting-wrap" v-if="showLinkmanSetting">
      <div class="form-title-wrap">
        <div class="form-title__left">{{ $t('smartPlan.linkmanSetting') }}</div>
        <div class="form-title__right tips">{{ $t('smartPlan.tips.tip11') }}</div>
      </div>
      <div class="linkman-setting-title mar-b-8">{{ $t('smartPlan.linkmanAndAddress') }}</div>
      <div class="linkman-setting-radio">
        <div class="linkman-setting-radio-item">
          <el-radio v-model="linkmanSetting" :label="0">{{ $t('smartPlan.customerDefaultLinkmanAndAddress') }}</el-radio>
          <el-tooltip :content="$t('smartPlan.tips.tip12')">
            <i class="iconfont icon-question-circle"></i>
          </el-tooltip>
        </div>
        <div class="linkman-setting-radio-item">
          <el-radio v-model="linkmanSetting" :label="1">{{ $t('smartPlan.productLinkmanAndAddress') }}</el-radio>
          <el-tooltip :content="$t('smartPlan.tips.tip13')">
            <i class="iconfont icon-question-circle"></i>
          </el-tooltip>
        </div>
      </div>
    </div>
    <preview-plan-range-dialog ref="previewPlanRangeDialog" />
  </div>
</template>

<script>
/* api */
import { getModuleList, getTriggerFieldList, checkLinkManSetting } from '@src/modules/smartPlan/api/index.js'
/* components */
import PreviewPlanRangeDialog from './previewPlanRangeDialog'
/* utils */
import { isEmpty, formatAddress } from 'pub-bbx-utils';
import { t } from '@src/locales'
import _ from 'lodash'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

export default {
  name: 'second-step',
  props: {
    bizType: {
      type: String,
      default: 'TASK'
    },
    fields: {
      type: Array,
      default: () => []
    },
    editConditions: {
      type: Array,
      default: () => []
    },
    editLinkmanSetting: {
      type: [Number, String],
      default: 0
    },
    customers: {
      type: Array,
      default: () => []
    },
    products: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      isInit: false,
      conditions: [],
      optionMaps: {},
      contractTriggerList: [],
      linkmanSetting: 0, // 联系人设置： 默认联系人
      hasMultiLinkman: false, // 是否有多个联系人
    }
  },
  computed: {
    /* 默认显示模块 */
    defaultModule() {
      if (this.customers.length) return ['customer']
      if (this.products.length) return ['product']
      return ['customer']
    },
    /* 默认显示条件 */
    defaultConditionItem() {
      if (this.customers.length) {
        return {
          fieldName: 'customerId',
          operator: 'in',
          value: this.customers,
          comp: 'customer-search',
          field: this.customerField
        }
      }
      if (this.products.length) {
        return {
          fieldName: 'productId',
          operator: 'in',
          value: this.products,
          comp: 'product-search',
          field: {
            displayName: t('common.base.product'),
            fieldName: 'product',
            formType: 'product',
          }
        }
      }
      return null
    },
    /* 客户字段 */
    customerField() {
      return this.fields.filter(f => f.formType === 'customer')[0];
    },
    /* 客户字段配置 */
    customerOption(){
      return (this.customerField?.setting && this.customerField?.setting?.customerOption) || {} ;
    },
    /* 产品字段 */
    productField() {
      return this.fields.filter(f => f.formType === 'product')[0];
    },
    /* 联系人字段 */
    linkmanField() {
      return this.fields.filter(f => f.formType === 'linkman')[0];
    },
    optionsList() {
      const list = []
      // 活动调研默认显示客户产品
      if (this.customerField || this.bizType == 'ACTIVITY_RESEARCH') {
        list.push({
          value: 'customer',
          label: t('common.base.customer'),
        })
      }
      if (this.customerOption.product || this.productField || this.bizType == 'ACTIVITY_RESEARCH') {
        list.push({
          value: 'product',
          label: t('common.base.product'),
        })
      }
      // 合同模块等会再写
      list.push({
        value: 'contract',
        label: t('contract.contract'),
        children: this.contractTriggerList
      })
      return list
    },
    // 是否显示联系人设置
    showLinkmanSetting() {
      return (this.linkmanField || this.customerField.linkman) && this.hasMultiLinkman
    },
  },
  watch: {
    editConditions: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.conditions = newValue || []
        const conditions = this.conditions.map(item => item.subCondition)
        this.changeValue(conditions)
      }
    },
    editLinkmanSetting: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.linkmanSetting = newValue || 0
      }
    },
  },
  created() {
    this.getContractTrigger()
  },
  async mounted() {
    if (this.products.length) {
      await this.getFieldList('PRODUCT')
      this.getFieldList('CUSTOMER')
    } else {
      await this.getFieldList('CUSTOMER')
      this.getFieldList('PRODUCT')
    }
    if (this.products.length || this.customers.length) {
      const conditions = [[{
        module: this.products.length ? ['product'] : ['customer'],
        conditionItem: this.defaultConditionItem
      }]]
      this.changeValue(conditions)
    }
  },
  methods: {
    async getFieldList(bizType, formId) {
      const res = await getTriggerFieldList({ bizType, formId })
      const data = (res.data || []).map(f => {
        if (f.fieldName == 'lmName') {
          f.formType = 'linkman'
        }
        if (bizType == 'CONTRACT') {
          f.formId = formId
        }
        return f
      })
      if (bizType == 'CUSTOMER') {
        data.push({
          displayName: t('common.base.createTime'),
          fieldName: 'createTime',
          isSystem: 1,
          formType: 'date',
        })
      } 
      this.optionMaps[bizType.toLowerCase()] = data
      this.isInit = true
    },
    getContractTrigger() {
      getModuleList({bizType: 'CONTRACT'}).then(res => {
        this.contractTriggerList = (res.data || []).map(item => {
          return {
            value: item.formId,
            label: item.name
          }
        })
      })
    },
    // 选择合同模板后获取合同表单数据
    async cascaderChange(formId, item, index) {
      if (this.optionMaps['contract']) {
        this.optionMaps['contract'] = []
      }
      await this.getFieldList('CONTRACT', formId)
      const conditions = this.$refs.baseSelectCondition.conditions
      const originFields = _.cloneDeep(this.optionMaps['contract'])
      this.optionMaps['contract'] = this.optionMaps['contract'].filter(f => {  
        // 判断当前同一条件组是否有已经存在的字段，已存在就过滤掉
        const conditionIndex = conditions.findIndex((condition, ind) => {  
          if (index == ind) {
            return condition.subCondition.some(item => {  
              const field = item.conditionItem?.field || {}
              return f.formId == field.formId && f.fieldName == field.fieldName
            })
          }
          return false
        })
        return conditionIndex === -1
      })
      this.$refs.baseSelectCondition.update(['contract'], item, index, originFields)
    },
    changeValue(conditions) {
      // 根据接口判断是否存在多个联系人
      if (this.linkmanField || this.customerField.linkman) {
        let params = this.buildParams()
        if (conditions && conditions.length) {
          params.conditions = conditions
        }
        checkLinkManSetting(this.bizType, params.conditions).then(res => {
          this.hasMultiLinkman = res.data || false
        })
      }
    },
    async validate() {
      const conditions = this.$refs.baseSelectCondition.conditions
      if (!conditions.length) return false
      let hasValue = false
      conditions.forEach(condition => {
        condition.subCondition.forEach(item => {
          if (!isEmpty(item.conditionItem?.value)) {
            hasValue = true
          }
        })
      })
      return hasValue
    },
    buildParams() {
      let conditions = this.$refs?.baseSelectCondition?.conditions || []
      conditions = conditions.map(item => item.subCondition).map(item => {
        // 过滤掉值为空的条件
        item = item.filter(condition => !isEmpty(condition.conditionItem.value))
        return item
      }).filter(item => item.length).map(item => {
        item.map(condition => {
          // 转为提交接口的字段
          condition.conditionItem.valueList = this.filterData(condition.conditionItem.comp, condition.conditionItem.value, condition.conditionItem.field)
          condition.conditionItem.valueStr = JSON.stringify(condition.conditionItem.value) 
          condition.conditionItem.formType = condition.conditionItem.field?.formType
          condition.conditionItem.isSystem = condition.conditionItem.field?.isSystem
          return condition
        })
        return item
      })
      return {
        linkmanSetting: this.hasMultiLinkman ? this.linkmanSetting : 0,
        conditions
      }
    },
    // 转换为提交的数据 valueList为数组格式
    filterData(comp, value, field) {
      let filterArr = []
      const setting = field.setting || {}
      if (['user-search', 'customer-search', 'tags-search', 'product-search', 'linkman-search'].includes(comp)) {
        if (Array.isArray(value)) return value.map(item => item.id)
        return [value].map(item => item.id);
      } else if (comp === 'select-search') {
        if (field.fieldName == 'customerTags') return [value]
        return value
      } else if (comp === 'cascader-search') {
        if (setting?.isMulti) {
          return value.map(item => item.join('/'))
        }
        return value
      } else if (comp === 'date-search' && Array.isArray(value)) {
        return value
      } else if (comp === 'address-search') {
        value = formatAddress(value, '')
        // 非国际化租户为了兼容老数据，需要把中国给去除
        if (!internationalGray && value.substring(0, 2) == '中国') {
          value = value.substring(2)
        }
        return [value]
      }
      // 其他类型的都转为数组
      filterArr.push(value)
      return filterArr
    },
    // 打开预览弹窗
    async openPreviewDialog() {
      let valid = await this.validate()
      if (valid) {
        const params = this.buildParams()
        this.$refs.previewPlanRangeDialog.open(params.conditions)
      } else {
        this.$platform.notification({
          title: this.$t('smartPlan.selectPlanRange'),
          type: 'error'
        })
      }
    },
  },
  components: {
    PreviewPlanRangeDialog,
  }
}
</script>

<style lang="scss">
.second-step-container {
  .form-title-wrap {
    width: 100%;
    height: 38px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    border-radius: 4px;
    background: #F7F8F8;
    margin-bottom: 16px;
    .form-title__left {
      font-weight: 500;
    }
    .form-title__right {
      font-size: 12px;
      &.tips {
        color: #8C8C8C;
      }
    }
  }
  .linkman-setting-wrap {
    padding: 16px 0;
    .linkman-setting-title {
      padding: 0 12px;
    }
    .linkman-setting-radio {
      display: flex;
      padding: 0 12px;
      &-item {
        margin-right: 24px;
        .el-radio {
          margin-right: 8px;
        }
        .icon-question-circle {
          font-size: 14px;
          color: #8C8C8C;
        }
      }
    }
  }
}
</style>